package com.company.chatRoom;

import com.company.utils.MyException;
import org.json.simple.JSONObject;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc    服务器接收线程，并且将接收数据分发到各个客户机
 */
public class ServerListen implements Runnable {
private Socket socket;

    public ServerListen(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            ObjectInputStream ois = Utils.getOISBySocket(socket);
            while (true){
                if(socket.getInputStream().available()>0){
//                    Object obj = ois.readObject();
                    HashMap<String, String> receive = (HashMap<String, String>)ois.readObject();
                    System.out.println(receive);
                    //服务器端接收分发
                    if(!"heart".equals(receive.get("type"))){
                        ServerSend.dispatch(receive);
                    }
                }

            }
        } catch (Exception e) {
            try {
                socket.close();
                MyException.logExceptionMessage(e);
                System.out.println("ServerListenner断开连接");
                ChatServer.closeAllThread();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }finally {
            try {
                socket.close();
            }catch (Exception e){
                MyException.logExceptionMessage(e);
            }
        }
    }
}
